package org.jeecg.modules.online.low.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.low.entity.LowApp;
import org.jeecg.modules.online.low.service.ILowAppMenuService;
import org.jeecg.modules.online.low.service.ILowAppService;
import org.jeecg.modules.online.low.vo.JeecgLicVo;
import org.jeecg.modules.online.low.vo.LowAppMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: low_app
 * @Author: jeecg-boot
 * @Date: 2021-07-13
 * @Version: V1.0
 */
//@Api(tags = "low_app")
@RestController("lowAppController")
@RequestMapping("/online/lowApp")
@Slf4j
public class LowAppController extends JeecgController<LowApp, ILowAppService> {
    @Autowired
    private ILowAppService lowAppService;
    @Autowired
    private ILowAppMenuService lowAppMenuService;

    /**
     * 分页列表查询
     *
     * @param lowApp
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "low_app-分页列表查询")
    //@ApiOperation(value = "low_app-分页列表查询", notes = "low_app-分页列表查询")
    @GetMapping(value = "/list")
    public Result queryPageList(
            LowApp lowApp,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req
    ) {
        QueryWrapper<LowApp> queryWrapper = QueryGenerator.initQueryWrapper(lowApp, req.getParameterMap());
        Page<LowApp> page = new Page<>(pageNo, pageSize);
        IPage<LowApp> pageList = lowAppService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 列表查询分组
     *
     * @param lowApp
     * @param req
     * @return
     */
    @GetMapping(value = "/listByGroup")
    public Result listByGroup(LowApp lowApp, HttpServletRequest req) {
        QueryWrapper<LowApp> queryWrapper = QueryGenerator.initQueryWrapper(lowApp, req.getParameterMap());
        queryWrapper.orderByDesc("app_label");
        queryWrapper.orderByAsc("order_num");
        queryWrapper.orderByDesc("create_time");
        List<LowApp> list = lowAppService.list(queryWrapper);
        // 通过 label 分组应用
        List<LowApp> noneChildren = new ArrayList<>();
        Map<String, List<LowApp>> map = new HashMap<>();
        for (LowApp data : list) {
            String appLabel = data.getAppLabel();
            if (StringUtil.isNotEmpty(appLabel)) {
                if (map.containsKey(appLabel)) {
                    map.get(appLabel).add(data);
                } else {
                    List<LowApp> children = new ArrayList<>();
                    children.add(data);
                    map.put(appLabel, children);
                }
            } else {
                noneChildren.add(data);
            }
        }
        JSONArray groupList = new JSONArray();
        JSONArray labelList = new JSONArray();
        for (String key : map.keySet()) {
            labelList.add(key);
            JSONObject groupItem = new JSONObject();
            groupItem.put("label", key);
            groupItem.put("list", map.get(key));
            groupList.add(groupItem);
        }
        if (noneChildren.size() > 0) {
            JSONObject groupItem = new JSONObject();
            groupItem.put("label", "无分组");
            groupItem.put("list", noneChildren);
            groupList.add(groupItem);
        }
        JSONObject res = new JSONObject();
        res.put("groupList", groupList);
        res.put("labelList", labelList);
        return Result.OK(res);
    }

    /**
     * 添加
     *
     * @param lowApp
     * @return
     */
    @AutoLog(value = "low_app-添加")
    //@ApiOperation(value = "low_app-添加", notes = "low_app-添加")
    @PostMapping(value = "/add")
    public Result add(@RequestBody LowApp lowApp) {
        lowAppService.createApp(lowApp);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param lowApp
     * @return
     */
    @AutoLog(value = "low_app-编辑")
    //@ApiOperation(value = "low_app-编辑", notes = "low_app-编辑")
    @PutMapping(value = "/edit")
    public Result edit(@RequestBody LowApp lowApp) {
        lowAppService.updateById(lowApp);
        return Result.OK("编辑成功!");
    }

    /**
     * 分组重命名
     *
     * @param payload
     * @return
     */
    @PutMapping(value = "/groupRename")
    public Result groupRename(@RequestBody JSONObject payload) {
        String newLabel = payload.getString("newLabel");
        String oldLabel = payload.getString("oldLabel");
        if (oConvertUtils.isEmpty(newLabel) || oConvertUtils.isEmpty(newLabel)) {
            return Result.error("分组名不能为空！");
        }
        // 更改旧label为新label
        LambdaQueryWrapper<LowApp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LowApp::getAppLabel, oldLabel);
        LowApp lowApp = new LowApp();
        lowApp.setAppLabel(newLabel);
        lowAppService.update(lowApp, queryWrapper);
        return Result.OK("重命名成功");
    }

    /**
     * 移动应用到分组（label）
     *
     * @param lowApp
     * @return
     */
    @PostMapping(value = "/moveToGroup")
    public Result moveToGroup(@RequestBody LowApp lowApp) {
        lowAppService.moveToGroup(lowApp);
        return Result.OK("移动成功！");
    }

    /**
     * 根据ID批量编辑
     *
     * @param lowAppList
     * @return
     */
    @AutoLog(value = "low_app-批量编辑")
    //@ApiOperation(value = "low_app-批量编辑", notes = "low_app-批量编辑")
    @PutMapping(value = "/editBatch")
    public Result editBatch(@RequestBody List<LowApp> lowAppList) {
        lowAppService.updateBatchById(lowAppList);
        return Result.OK("批量编辑成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "low_app-通过id删除")
    //@ApiOperation(value = "low_app-通过id删除", notes = "low_app-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result delete(@RequestParam(name = "id") String id) {
        lowAppService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "low_app-批量删除")
    //@ApiOperation(value = "low_app-批量删除", notes = "low_app-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result deleteBatch(@RequestParam(name = "ids") String ids) {
        this.lowAppService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "low_app-通过id查询")
    //@ApiOperation(value = "low_app-通过id查询", notes = "low_app-通过id查询")
    @GetMapping(value = "/queryById")
    public Result queryById(@RequestParam(name = "id") String id) {
        LowApp lowApp = lowAppService.getById(id);
        if (lowApp == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(lowApp);
    }

    /**
     * 通过ID查询应用详情，包括菜单
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryDetail")
    public Result<?> queryDetail(@RequestParam(name = "id") String id) {
        LowApp lowApp = lowAppService.getById(id);
        if (lowApp == null) {
            return Result.error(404, "未找到对应数据");
        }
        List<LowAppMenuVo> menuList = lowAppMenuService.listAndChildren(id);
        JSONObject json = new JSONObject();
        json.put("record", lowApp);
        json.put("menuList", menuList);
        return Result.OK(json);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param lowApp
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LowApp lowApp) {
        return super.exportXls(request, lowApp, LowApp.class, "low_app");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LowApp.class);
    }

    /**
     * //TODO假接口
     * 授权检查
     * @return
     */
    @RequestMapping(value = "/checkAuth", method = RequestMethod.POST)
    public Result<?> checkCaptcha(@RequestBody JeecgLicVo jeecgLic) {
        String licenceId = jeecgLic.getLicenceId();
        String licenceKey = jeecgLic.getLicenceKey();
        if (licenceId == null || licenceKey == null) {
            return Result.error("请填写授权码");
        }

        if (licenceId.equals("jeecg") && licenceKey.equals("1111111111")) {
            return Result.OK("授权通过");
        } else {
            return Result.error("授权码无效");
        }
    }
}
